<template>
  <div class="formItem">
    <el-form-item
      v-if="widget"
      :prop="widget.tableFieldName || widget.fieldName"
      :label="widget.fieldConfig.unit? widget.fieldName+ '('+ widget.fieldConfig.unit+')': widget.fieldName"
      :rules="rf_rules({required:widget.fieldConfig.required})"
    >
      <template v-if="widget.customType == 'input'">
        <el-input
          v-model="vm[widget.tableFieldName || widget.fieldName]"
          :placeholder="widget.fieldConfig.placeholder"
          :disabled="widget.fieldConfig.disabled || disabled"></el-input>
      </template>
      <template v-if="widget.customType == 'number'">
        <el-input-number
          v-model="vm[widget.tableFieldName || widget.fieldName]"
          :precision="parseInt(widget.fieldConfig.precision || 0)"
          :placeholder="widget.fieldConfig.placeholder"
          :disabled="widget.fieldConfig.disabled || disabled"></el-input-number>
      </template>
      <template v-if="widget.customType == 'textarea'">
        <el-input type="textarea" :rows="5"
                  v-model="vm[widget.tableFieldName || widget.fieldName]"
                  :disabled="widget.fieldConfig.disabled || disabled"
                  :placeholder="widget.fieldConfig.placeholder"></el-input>
      </template>
      <template v-if="widget.customType == 'date'">
        <el-date-picker
          v-model="vm[widget.tableFieldName||widget.fieldName]"
          value-format="yyyy-MM-dd"
          :type="widget.fieldConfig.type"
          :placeholder="widget.fieldConfig.placeholder"
          :readonly="widget.fieldConfig.readonly"
          :disabled="widget.fieldConfig.disabled || disabled"
          :editable="widget.fieldConfig.editable"
          :clearable="widget.fieldConfig.clearable"
        >
        </el-date-picker>
      </template>
      <template v-if="widget.customType == 'select'">
        <el-select v-model="vm[widget.tableFieldName || widget.fieldName]"
                   :clearable="widget.fieldConfig.clearable"
                   :disabled="widget.fieldConfig.disabled || disabled"
                   :placeholder="widget.fieldConfig.placeholder"
                   @change="changeSelect"
        >
          <el-option
            v-for="item in apiData"
            :key="item[widget.fieldConfig.value]"
            :label="item[widget.fieldConfig.label]"
            :value="item[widget.fieldConfig.value]">
          </el-option>
        </el-select>
      </template>
      <template v-if="widget.customType == 'autocomplete'">
        <el-autocomplete
          v-model="vm[widget.tableFieldName || widget.fieldName]"
          :debounce="500"
          :fetch-suggestions="querySearchAsync"
          placeholder="请输入"
          :value-key="widget.fieldConfig.valueKey"
          @select="changeAutoComplete"
        ></el-autocomplete>
      </template>
    </el-form-item>
  </div>
</template>

<script>
  import {mapGetters} from 'vuex'
  import api from '../../../utils/api'
  import util from '../../../utils/util'
  export default {
    name: 'previewFormItem',
    components: {
    },
    props: {
      element: {
        type: Object,
        default () {
          return {}
        }
      },
      vm: { // model绑定的数据
        type: Object,
        default () {
          return {}
        }
      },
      'index': {
        type: Number
      },
      'data': {},
      listKey: {
        type: String,
        default: 'list'
      },
      disabled: {
        type: Boolean,
        default: false
      }
    },
    data () {
      return {
        widget: null,
        apiData: null // 接口请求的数据
      }
    },
    computed: {
      ...mapGetters(['hasChoose'])
    },
    watch: {
      element: {
        handler (val) {
          if (val.customType && val.type !== 'table') {
            if (typeof val.fieldConfig === 'string') {
              val.fieldConfig = JSON.parse(val.fieldConfig)
            }
            this.widget = {...val}
            this.initData()
          }
        },
        immediate: true
      },
      vm: {
        handler (val) {
          this.$forceUpdate() // 刷新组件。重新渲染
        },
        deep: true
      }
    },
    methods: {
      initData () {
        switch (this.widget.customType) {
          case 'select':
            console.log(this.widget.fieldConfig.params)
            let params = this.widget.fieldConfig.params ?  eval("("+ this.widget.fieldConfig.params + ")") : ''
            api.formCommonApi(this.widget.fieldConfig.url, params).then((res) => {
              if (res.code === api.SUCCESS) {
                this.apiData = res.data
              }
            }).catch((res) => {
            })
            break
        }
      },
      querySearchAsync (queryString, callback) {
        let params = this.widget.fieldConfig.params ?  eval("("+ this.widget.fieldConfig.params + ")") : {}
        params.keyword = queryString
        api.formCommonApi(this.widget.fieldConfig.url, params).then((res) => {
          if (res.code === api.SUCCESS) {
            callback(res.data)
          }
        }).catch((res) => {
        })
      },
      // el-autocomplete 下拉选择改变
      changeAutoComplete (item) {
        this.setRelatedFieldVal(item)
        this.$parent.validateField(this.widget.tableFieldName || this.widget.fieldName)
      },
      // 下拉选择改变
      changeSelect (value) {
        let idStr = this.widget.fieldConfig.value // 获取key值，一般指代id 或 code
        let lableStr = this.widget.fieldConfig.label // 获取label值，一般指代name
        let tmp = util.getObjInArr(this.apiData, idStr, value) //  根据key回查对应object，再获取对应的label，设置在vm中
        let fieldStr = this.widget.tableFieldName || this.widget.fieldName
        fieldStr += '_str'
        this.vm[fieldStr] = tmp[lableStr]
        this.setRelatedFieldVal(tmp)
      },
      // 带出关联字段的值
      setRelatedFieldVal (tmp) {
        if (!this.widget.fieldConfig.relatedFields) return
        this.widget.fieldConfig.relatedFields.forEach(item => {
          /*this.vm[item.fieldName] = tmp[item.relatedKey]
          this.vm[item.tableFieldName] = tmp[item.relatedKey]*/
          this.$set(this.vm, item.fieldName, tmp[item.relatedKey])
          this.$set(this.vm, item.tableFieldName, tmp[item.relatedKey])
        })
      },
      dragleave () {
        this.isOver = false
      },
      handleSelectWidget (index) {
        // this.selectWidget = JSON.parse(JSON.stringify(this.data[this.listKey][index]))
      },
      // 删除组件
      delWidget () {
        this.widget = {}
        this.isOver = false
      }
    }
  }
</script>

<style lang="scss" scoped>
  .formItem {
    padding: 0 10px;
    box-sizing: border-box;
    .el-select,.el-autocomplete {
      width: 100%;
    }
    .el-input-number, .el-date-editor {
      width: 100%;
      .el-input__inner {text-align: left}
    }
  }
  .line-width-1 {
    width: 100%;
  }
  .widget-view {
    min-height: 100px;
    margin: 5px;
    border: 1px solid #ddd;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    .title {
      text-align: center;
      height: 23px;
      line-height: 23px;
      border-bottom: 1px solid #ddd;
      width: 100%;
    }
    .widgetBox {
      display: flex;
      flex: 1;
      align-items: center;
      justify-content: center;
      position: relative;
      width: 100%;
      padding: 5px;
      .widget-btn-pane {
        position: absolute;
        right: 10px;
        top: 3px;
        height: 23px;
        width: 23px;
        box-shadow: 0 2px 4px 0 #ddd;
        background-color: #fff;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        &:hover {
          color: #d84636;
          background-color: #FDECEC;
        }
      }
      .sortable-chosen {
        display: none;
      }
      .dragBox {
        height: 100%;
        width: 100%;
        position: absolute;
        left: 0;
        right: 0;
        &.forbidden-childe-pointer-events * {
          pointer-events: none;
        }
      }
      .emptyBox {
        height: 100%;
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        pointer-events: none;
      }
      .noneContent {
        color: #91A1B7
      }
    }
    .el-form-item__label {
      background-color: rgba(0,0,0,0);
    }
    .el-form-item {
      margin-bottom: 0;
      width: 100%;
    }

    .widgetTableBox {
      padding: 0;
    }
  }
  .widget-view:hover {
    background-color: #F5F7FA;
  }
  .widget-view.active {
    background-color: #DEF1FF;
  }

  .subform-content {
    display: flex;
    .row-head {
      width: 68px;
      .head-label {
        background: #fff;
        border-right: 1px solid #eee;
        border-bottom: 1px solid #eee;
        width: 68px;
        height: 35px;
        border-top-left-radius: 3px;
      }
      .row-num {
        height: 40px;
        line-height: 40px;
        text-align: center;
        background: #fcfcfd;
        border-right: solid 1px #eee;
      }
    }
  }
</style>
